package com.commerceerp.system.pay;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;


public class CommonUtil {

	/**
	 * 通用工具类
	 */
	private static Logger log = Logger.getLogger(CommonUtil.class);

	/**
	 * 生成随机字符串
	 * 
	 * @param length
	 *            长度
	 * @return 生成的字符串
	 */
	public static String getRandomString(int length) {
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	/**
	 * http请求
	 * 
	 * @param requestUrl
	 * @param requestMethod
	 * @param output
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 * @throws KeyManagementException
	 * @throws MalformedURLException
	 * @throws IOException
	 * @throws ProtocolException
	 * @throws UnsupportedEncodingException
	 */
	private static StringBuffer httpsRequest(String requestUrl, String requestMethod, String output)
			throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, MalformedURLException,
			IOException, ProtocolException, UnsupportedEncodingException {
		URL url = new URL(requestUrl);
		HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setUseCaches(false);
		connection.setRequestMethod(requestMethod);
		if (null != output) {
			OutputStream outputStream = connection.getOutputStream();
			outputStream.write(output.getBytes("UTF-8"));
			outputStream.close();
		}

		// 从输入流读取返回内容
		InputStream inputStream = connection.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String str = null;
		StringBuffer buffer = new StringBuffer();
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		bufferedReader.close();
		inputStreamReader.close();
		inputStream.close();
		inputStream = null;
		connection.disconnect();
		return buffer;
	}

	public static Map<String, String> httpsRequestToXML(String requestUrl, String requestMethod, String outputStr) {
		Map<String, String> result = new HashMap<String, String>();
		try {
			StringBuffer buffer = httpsRequest(requestUrl, requestMethod, outputStr);
			result = parseXml(buffer.toString());
		} catch (ConnectException ce) {
			log.error("连接超时：" + ce.getMessage());
		} catch (Exception e) {
			log.error("https请求异常：" + e.getMessage());
		}
		return result;
	}

	/**
	 * xml转Map
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> parseXml(String xml) throws Exception {
		Map<String, String> map = new HashMap<String, String>();

		Document document = DocumentHelper.parseText(xml);
		Element root = document.getRootElement();
		List<Element> elementList = root.elements();

		for (Element e : elementList)
			map.put(e.getName(), e.getText());
		return map;
	}

	/**
	 * InputStream流转换成String字符串
	 * @param inStream InputStream流
	 * @param encoding 编码格式
	 * @return String字符串
	 */
	public static String inputStream2String(InputStream inStream, String encoding){
		String result = null;
		try {
			if(inStream != null){
				ByteArrayOutputStream outStream = new ByteArrayOutputStream();
				byte[] tempBytes = new byte[1024*1000];
				int count = -1;
				while((count = inStream.read(tempBytes, 0,1024*1000)) != -1){
					outStream.write(tempBytes, 0, count);
				}
				tempBytes = null;
				outStream.flush();
				result = new String(outStream.toByteArray(), encoding);
			}
		} catch (Exception e) {
			result = null;
		}
		return result;
	}

    /**
     * 将map 转化成 xml
     * @param map
     * @return
     */
    public static String mapToXml(Map<String,String> map)throws Exception{
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sb.append("<" + entry.getKey() + ">" + entry.getValue().toString() + "</" + entry.getKey() + ">");
        }
        sb.append("</xml>");
        return sb.toString();
    }
}
